package org.example.algorithm.dynamicProgramming;

/**
 * @Description: 最大连续子序列和
 */

public class TestMaxSubArray {
    public static void main(String[] args) {
        int[] nums = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println(maxSubArray_1(nums));
    }

    // 最大连续子序列和
    static int maxSubArray_1(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];
        // dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
        int max = nums[0];
        dp[0] = nums[0];
        for (int i = 1; i < n; i++) {
            dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
            if (dp[i] >= max) {
                max = dp[i];
            }
        }
        return max;
    }

    static int maxSubArray_2(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];
        int max = nums[0];
        dp[0] = nums[0];
        for (int i = 1; i < n; i++) {
            // 抽出 nums[i]
//            dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
            dp[i] = nums[i] + Math.max(dp[i - 1], 0);
            max = Math.max(dp[i], max);
        }
        return max;
    }
}
